import React, { useCallback, useEffect, useRef, useState } from 'react';
import { View, Image, Text } from '@tarojs/components';
import Autograph from './autogroph';
// import {APP_URLS} from '@/utils/api/api_urls'
// import { upload } from '@/utils/api/httpRequest'
import './index.scss'
import PopupLayer from '../popupLayer';
import { getImagePath } from '../../utils';

const Index = (props) =>{
  const [imgSrc, setImgSrc] = useState('');
  const [file, setFile] = useState({});
  const popupPef = useRef(null);
  // const { onChange } = props;
  const open = useCallback(() =>{
    popupPef.current.show();
  },[]);

  const close = useCallback(() =>{
    popupPef.current.close();
  },[]);

  const autographOnChange = (fileId,fileCode)=>{
    close();
    setFile({
      fileId,
      fileCode
    });
    setImgSrc(getImagePath(fileId,fileCode));
    // onChange(fileId,fileCode);
  }

  // 放开对外控制
  useEffect(() => {
    const action = {
      getFile: ()=>{
        return file
      }
    };
    const { actionRef } = props;
    if (actionRef && typeof actionRef !== 'function') {
      actionRef.current = action;
    }
  }, [file]);

  return (
    <View className='signature'>
      <View className='signature-body' onClick={open}>
        {
          imgSrc ? (
            <Image
              src={imgSrc}
              className='img'
            />
          ): (
            <View className='img-default'>
              <Text>请在此处签名</Text>
            </View>
          )
        }
      </View>
      <PopupLayer
        id='popupRef'
        direction='top'
        ref={popupPef}
      >
        <Autograph onChange={autographOnChange} />
      </PopupLayer>
    </View>
  )
}

export default React.memo(Index);
